//
//  oldMapSearchViewController.m
//  laonianbang
//
//  Created by 勇拓 李 on 18/3/29.
//  Copyright © 2018年 zaiyou. All rights reserved.
//

#import "oldMapSearchViewController.h"
#import "oldMapSearchTableViewCell.h"
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
#import "oldMapSearchHeaderView.h"
#import "JFCityViewController.h"
#import "oldBasedModel.h"
#import "oldMapLocationViewController.h"

@interface oldMapSearchViewController ()<BMKSuggestionSearchDelegate, JFCityViewControllerDelegate>
@property (nonatomic, strong)BMKSuggestionSearch *searcher;
@property (nonatomic, strong)BMKSuggestionSearchOption *option;
@property (nonatomic, strong)NSMutableArray *searchResultArray;
@property (nonatomic, strong)oldMapSearchHeaderView *headerView;
@end

static NSString * const reuseIdentifier = @"oldMapSearchTableViewCell";

@implementation oldMapSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    [self initData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    _searcher.delegate = nil;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark - initView
- (void)initView
{
    self.navigationItem.title = @"地址搜索";
    [self rigisterCell:reuseIdentifier];
    [self initHeader];
}

- (void)initHeader
{
    _headerView = [[[NSBundle mainBundle] loadNibNamed:@"oldMapSearchHeaderView" owner:self options:nil] objectAtIndex:0];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(textFieldDidChangeValue:)
                                                 name:UITextFieldTextDidChangeNotification
                                               object:_headerView.text_field];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(chooseCity:)];
    [_headerView addGestureRecognizer:tap];
    
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 39)];
    
    self.tableView.tableHeaderView = header;
    _headerView.frame = header.bounds;
    [header addSubview:_headerView];
}

- (void)beignSearch:(NSString *)cityname keyword:(NSString *)keyword
{
    //初始化检索对象
    _searcher = [[BMKSuggestionSearch alloc] init];
    _searcher.delegate = self;
    _option = [[BMKSuggestionSearchOption alloc] init];
    _option.cityname = cityname;
    _option.keyword  = keyword;
    BOOL flag = [_searcher suggestionSearch:_option];
    if(flag)
    {
        NSLog(@"建议检索发送成功");
    }
    else
    {
        NSLog(@"建议检索发送失败");
    }
}

#pragma mark - initData
- (void)initData
{
    _headerView.label_city.text = @"选择城市";
    
    _searchResultArray = [NSMutableArray array];
    if (!_city) {
        NSArray *historyArray = [NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:@"historyCity"]];
        if ([historyArray count]) {
            _city = historyArray[0];
            _headerView.label_city.text = _city;
        }
    }
}

#pragma mark - city
- (void)chooseCity:(id)sender
{
    JFCityViewController *cityViewController = [[JFCityViewController alloc] init];
    //  设置代理
    cityViewController.delegate = self;
    cityViewController.title = @"城市";
    //  给JFCityViewController添加一个导航控制器
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:cityViewController];
    [self presentViewController:navigationController animated:YES completion:nil];
}

- (void)cityName:(NSString *)name
{
    _city = name;
    _headerView.label_city.text = _city;
}

#pragma mark - textFiled
- (void)textFieldDidChangeValue:(NSNotification *)notification
{
    UITextField *sender = (UITextField *)[notification object];
    if ([sender.text length]) {
        [self beignSearch:_city keyword:sender.text];
    }
}

#pragma mark - 在线建议查询代理
//实现Delegate处理回调结果
- (void)onGetSuggestionResult:(BMKSuggestionSearch*)searcher result:(BMKSuggestionResult*)result errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
        if (_searchResultArray.count != 0) {
            [_searchResultArray removeAllObjects];
        }
        //在此处理正常结果
        for (int i = 0; i < result.keyList.count; i++) {
            oldAddressInfo *model = [[oldAddressInfo alloc] init];
            model.address = result.keyList[i];
            CLLocationCoordinate2D coor;
            [result.ptList[i] getValue:&coor];
            model.lat = [NSString stringWithFormat:@"%f", coor.latitude];
            model.lng = [NSString stringWithFormat:@"%f", coor.longitude];
            [_searchResultArray addObject:model];
        }
        
        [self.tableView reloadData];
    }
    else {
        NSLog(@"抱歉，未找到结果");
    }
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [_searchResultArray count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    oldMapSearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    if (cell == nil) {
        cell = [[oldMapSearchTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    }
    
    oldAddressInfo *model = _searchResultArray[indexPath.row];
    
    cell.label_title.text = model.address;
    if (0 == indexPath.row) {
        cell.btn_location.hidden = NO;
    }
    else
    {
        cell.btn_location.hidden = YES;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 55;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UIViewController *vc = self.navigationController.viewControllers[[self.navigationController.viewControllers count] - 2];
    
    if ([vc isKindOfClass:[oldMapLocationViewController class]]) {
        oldMapLocationViewController *oldVc = (oldMapLocationViewController *)vc;
        oldVc.addressInfo = _searchResultArray[indexPath.row];
    }
    [self.navigationController popViewControllerAnimated:YES];
    
}

@end
